﻿//#define DIAGNOSTICS

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mathematics;
using Mathematics.Expressions;
using Mathematics.Parser;

namespace MathConsole
{
    public static class Commands
    {
        public static readonly string EXIT = @"^exit\s";
        public static readonly string RUN = @"^run\s";
        public static readonly string CLEAR = @"^clear\s";
        public static readonly string RESET = @"^reset\s";
        public static readonly string HELP = @"^[\?]\s";

        private static readonly Regex EXIT_REGEX = new Regex(EXIT);
        private static readonly Regex RUN_REGEX = new Regex(RUN);
        private static readonly Regex CLEAR_REGEX = new Regex(CLEAR);
        private static readonly Regex REST_REGEX = new Regex(CLEAR);
        private static readonly Regex HELP_REGEX = new Regex(HELP);

        public static bool EvaluateCommands(string input)
        {
            //try
            //{
            if (EXIT_REGEX.IsMatch(input))
                return false;
            else if (RUN_REGEX.IsMatch(input))
                RunFile(input);
            else if (HELP_REGEX.IsMatch(input))
                DisplayHelp(input);
            else if (CLEAR_REGEX.IsMatch(input))
                Clear();
            else if (REST_REGEX.IsMatch(input))
                Reset();
            else
                InterpretInput(input);
            //}
            //catch (Exception ex)
            //{
            //    Console.ForegroundColor = ConsoleColor.Red;
            //    Console.WriteLine(ex.Message);
            //    Console.ForegroundColor = ConsoleColor.White;
            //}
            return true;
        }

        public static void Reset()
        {
            Domain.ResetRoot();
        }

        public static void Clear()
        {
            Console.Clear();
        }

        private static void InterpretInput(string input)
        {
#if DIAGNOSTICS
            var watch = new Stopwatch();
            watch.Start();
#endif

            Interpreter.EvaluateLine(input);

#if DIAGNOSTICS
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
#endif
        }

        private static void DisplayHelp(string input)
        {
            throw new NotImplementedException();
        }

        private static void RunFile(string input)
        {
            var parts = RUN_REGEX.Split(input);
            var pathString = parts[1].Trim();

            if (!File.Exists(pathString))
                throw new ArgumentException(string.Format("Path '{0}' does not exist", pathString));

            Interpreter.EvaluateFile(pathString);
        }
    }
}
